/**
 * 简单的天气应用，使用Framework7
 */
var myApp = new Framework7({
	precompileTemplates: true,
	modalTitle: "提示"
});
var $$ = Dom7;

var mainView = myApp.addView('.view-main', {
	dynamicNavbar: true
});

// 初始化
var citys = [];
var default_citys = ["北京", "广州"];
var hot_citys = ["保定", "北京", "长春", "成都", "重庆", "长沙", "常熟", "朝阳", "常州", "东莞", "大连", "佛山", "福州", "桂林", "贵阳", "广州", "哈尔滨", "合肥", "呼和浩特", "海口", "杭州", "惠州", "湖州", "金华", "江门", "济南", "济宁", "嘉兴", "江阴", "昆明", "昆山", "聊城", "廊坊", "洛阳", "临沂", "兰州", "柳州", "马鞍山", "绵阳", "宁波", "南昌", "南京", "南宁", "南通", "青岛", "泉州", "上海", "石家庄", "汕头", "绍兴", "沈阳", "深圳", "苏州", "天津", "唐山", "太原", "台州", "潍坊", "武汉", "芜湖", "威海", "乌鲁木齐", "无锡", "温州", "西安", "香港", "厦门", "西宁", "徐州", "银川", "运城", "盐城", "烟台", "珠海", "肇庆", "中山", "郑州"];

// ----------------- 逻辑处理
var app = {
	init: function() {
		// 初始化本地城市信息
		this.initLocalCitys();
		// 初始化热门城市列表
		this.renderHotCitys();
	},
	initLocalCitys: function() {
		if (!localStorage.citys) {
			localStorage.citys = JSON.stringify(default_citys);
		}
		citys = JSON.parse(localStorage.citys);
		this.getWeather();
	},

	// 保存到LocalStorage
	saveCity: function() {
		localStorage.citys = JSON.stringify(citys);
	},

	renderHotCitys: function() {
		var html = Template7.templates.cityTemplate(hot_citys);
		$$("#hotCityList").html(html);
	},
	/**
	 *
	 * @param {Object} city
	 * @param {Object} callback
	 */
	renderWeather: function(city, callback) {
		this.getCityWeather(city, function(data) {
			var temp = [data];
			var html = Template7.templates.indexTemplate(temp);
			$$("#city").prepend(html);
			callback();
		});
	},
	/**
	 * 获取某个城市的天气
	 * @param {Object} city
	 * @param {Object} callback
	 */
	getCityWeather: function(city, callback) {
		var url = "http://apistore.baidu.com/microservice/weather?cityname=" + city;
		Util.ajaxGet(url, function(ret) {
			var data = ret.retData;
			callback(data);
		});
	},

	/**
	 * 遍历所有城市，获取天气数据
	 * @param {Object} refresh 如果是刷新，则添加下拉刷新事件
	 */
	getWeather: function(refresh) {
		myApp.showIndicator();
		var city_datas = [];
		$$.each(citys, function(i, item) {
			app.getCityWeather(item, function(data) {
				city_datas[i] = data;
				// 数据都更新完才刷新
				if (city_datas.length == citys.length) {
					var html = Template7.templates.indexTemplate(city_datas);
					$$("#city").html(html);
					myApp.hideIndicator();
					if (refresh) {
						myApp.pullToRefreshDone();
					}
				}
			});
		});
	}
};

var Util = {
	ajaxGet: function(url, callback) {
		var api = "http://cnionic.com/cross.php";
		$$.post(api, {
			url: url
		}, function(ret) {
			ret = ret ? JSON.parse(ret) : '';
			callback(ret);
		});
	}
}

// --------------- 事件---------------
// 主页初始化，需要使用trigger
myApp.onPageInit('index', function(page) {
	app.init();
}).trigger();

// 下拉刷新
$$('.pull-to-refresh-content').on('refresh', function(e) {
	app.getWeather(true);
});
// swipeout删除
$$('#city').on('deleted', '.swipeout', function() {
	var id = $$(this).attr("data-id");
	citys.splice(id, 1); // 这里删除后，数组的索引被破坏，需要重建
	app.saveCity();
});
// 添加城市列表 
$$("#hotCityList").on("click", ".cityItem", function(e) {
	var city = $$(this).attr("_value");
	if (citys.indexOf(city) < 0) {
		// 新加入的放在前面，写入缓存，并且马上刷新到天气中
		citys.unshift(city);
		app.saveCity();
		app.renderWeather(city, function() {
			myApp.closeModal();
		});
	} else {
		myApp.alert(city + "已经存在.");
	}
});

// 检查更新
window.addEventListener('load', function(e) {
	window.applicationCache.addEventListener('updateready', function(e) {
		if (window.applicationCache.status === window.applicationCache.UPDATEREADY) {
			myApp.confirm('发现新版本，马上更新？', function() {
				window.location.reload();
			});
		} else {
			// Manifest没有更新.
		}
	}, false);
}, false);